<template>
	<view class="container">
		<!-- 聊天头部 -->
		<view class="chat-header">
			<view class="header-left">
				<image class="user-avatar" :src="chatUser.avatar" mode="aspectFill"></image>
				<view class="user-info">
					<text class="user-name">{{ chatUser.name }}</text>
					<text class="user-status">{{ chatUser.online ? '在线' : '离线' }}</text>
				</view>
			</view>
			<view class="header-right">
				<view class="more-btn" @click="showMenu">⋮</view>
			</view>
		</view>

		<!-- 消息列表 -->
		<scroll-view 
			class="message-list" 
			scroll-y 
			:scroll-into-view="scrollToView"
			:scroll-with-animation="true">
			
			<view class="message-wrapper" v-for="(msg, index) in messages" :key="msg.id" :id="'msg-' + msg.id">
				<!-- 时间分割线 -->
				<view class="time-divider" v-if="showTimeDivider(index)">
					<text class="time-text">{{ msg.time }}</text>
				</view>

				<!-- 消息项 -->
				<view class="message-item" :class="msg.isMine ? 'mine' : 'other'">
					<!-- 头像 -->
					<image 
						v-if="!msg.isMine" 
						class="msg-avatar" 
						:src="chatUser.avatar" 
						mode="aspectFill"></image>

					<!-- 消息内容 -->
					<view class="message-content">
						<!-- 文字消息 -->
						<view v-if="msg.type === 'text'" class="text-message">
							<text class="message-text">{{ msg.content }}</text>
						</view>

						<!-- 图片消息 -->
						<image 
							v-else-if="msg.type === 'image'" 
							class="image-message" 
							:src="msg.content" 
							mode="aspectFill"
							@click="previewImage(msg.content)"></image>

						<!-- 订单卡片 -->
						<view v-else-if="msg.type === 'order'" class="order-message" @click="viewOrder(msg.orderId)">
							<view class="order-header">
								<text class="order-icon">📋</text>
								<text class="order-title">订单信息</text>
							</view>
							<view class="order-info">
								<text class="order-pet">{{ msg.orderInfo.petName }}</text>
								<text class="order-service">{{ msg.orderInfo.serviceType }}</text>
								<text class="order-price">¥{{ msg.orderInfo.price }}</text>
							</view>
						</view>
					</view>

					<!-- 头像（我的消息） -->
					<image 
						v-if="msg.isMine" 
						class="msg-avatar" 
						:src="myAvatar" 
						mode="aspectFill"></image>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<text class="load-text">加载更多消息</text>
			</view>
		</scroll-view>

		<!-- 输入区域 -->
		<view class="input-area">
			<!-- 工具栏 -->
			<view class="toolbar">
				<view class="tool-btn" @click="sendImage">
					<text class="tool-icon">📷</text>
				</view>
				<view class="tool-btn" @click="sendOrder">
					<text class="tool-icon">📋</text>
				</view>
			</view>

			<!-- 输入框 -->
			<view class="input-wrapper">
				<textarea 
					class="message-input" 
					v-model="inputText" 
					:adjust-position="true"
					:auto-height="true"
					:maxlength="500"
					placeholder="输入消息..."
					@confirm="sendMessage" />
				<button class="send-btn" :disabled="!inputText.trim()" @click="sendMessage">
					发送
				</button>
			</view>

			<!-- 快捷回复 -->
			<scroll-view class="quick-replies" scroll-x v-if="quickReplies.length > 0">
				<view 
					class="quick-item" 
					v-for="(item, index) in quickReplies" 
					:key="index"
					@click="selectQuickReply(item)">
					{{ item }}
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userId: null,
			chatUser: {
				id: '1001',
				name: '张小宠',
				avatar: '/static/avatar1.png',
				online: true
			},
			myAvatar: '/static/avatar2.png',
			messages: [],
			inputText: '',
			scrollToView: '',
			hasMore: false,
			quickReplies: [
				'已到门口',
				'服务完成',
				'请问宠物有什么特殊要求吗？',
				'好的，了解了',
				'谢谢'
			]
		}
	},
	onLoad(options) {
		if (options.userId) {
			this.userId = options.userId
		}
		if (options.userName) {
			this.chatUser.name = options.userName
		}
		this.loadMessages()
	},
	methods: {
		// 加载消息
		loadMessages() {
			// 模拟加载历史消息
			this.messages = [
				{
					id: 1,
					type: 'text',
					content: '你好，请问什么时候可以上门服务？',
					time: '10:30',
					isMine: false
				},
				{
					id: 2,
					type: 'text',
					content: '您好，我今天下午2点可以',
					time: '10:32',
					isMine: true
				},
				{
					id: 3,
					type: 'text',
					content: '好的，那下午2点见',
					time: '10:35',
					isMine: false
				},
				{
					id: 4,
					type: 'text',
					content: '请问您家宠物有什么特殊要求吗？',
					time: '10:36',
					isMine: true
				},
				{
					id: 5,
					type: 'text',
					content: '咪咪比较怕生，请轻声说话就好',
					time: '10:38',
					isMine: false
				}
			]
			
			this.scrollToBottom()
		},

		// 是否显示时间分割线
		showTimeDivider(index) {
			if (index === 0) return true
			// 简化处理：每5条消息显示一次时间
			return index % 5 === 0
		},

		// 发送文字消息
		sendMessage() {
			if (!this.inputText.trim()) return

			const newMsg = {
				id: Date.now(),
				type: 'text',
				content: this.inputText.trim(),
				time: this.getCurrentTime(),
				isMine: true
			}

			this.messages.push(newMsg)
			this.inputText = ''
			this.scrollToBottom()

			// 模拟对方回复
			setTimeout(() => {
				this.receiveMessage({
					id: Date.now(),
					type: 'text',
					content: '收到，谢谢',
					time: this.getCurrentTime(),
					isMine: false
				})
			}, 1000)
		},

		// 发送图片
		sendImage() {
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: (res) => {
					const newMsg = {
						id: Date.now(),
						type: 'image',
						content: res.tempFilePaths[0],
						time: this.getCurrentTime(),
						isMine: true
					}
					this.messages.push(newMsg)
					this.scrollToBottom()
				}
			})
		},

		// 发送订单
		sendOrder() {
			uni.showToast({
				title: '订单卡片功能开发中',
				icon: 'none'
			})
		},

		// 选择快捷回复
		selectQuickReply(text) {
			this.inputText = text
		},

		// 接收消息
		receiveMessage(msg) {
			this.messages.push(msg)
			this.scrollToBottom()
		},

		// 滚动到底部
		scrollToBottom() {
			this.$nextTick(() => {
				if (this.messages.length > 0) {
					const lastMsg = this.messages[this.messages.length - 1]
					this.scrollToView = 'msg-' + lastMsg.id
				}
			})
		},

		// 预览图片
		previewImage(url) {
			const images = this.messages
				.filter(msg => msg.type === 'image')
				.map(msg => msg.content)
			
			uni.previewImage({
				urls: images,
				current: url
			})
		},

		// 查看订单
		viewOrder(orderId) {
			uni.navigateTo({
				url: `/pages/order-detail/order-detail?id=${orderId}`
			})
		},

		// 显示菜单
		showMenu() {
			uni.showActionSheet({
				itemList: ['查看订单', '清空聊天记录', '举报'],
				success: (res) => {
					if (res.tapIndex === 0) {
						// 查看订单
						uni.showToast({ title: '订单功能开发中', icon: 'none' })
					} else if (res.tapIndex === 1) {
						// 清空聊天记录
						this.clearMessages()
					} else if (res.tapIndex === 2) {
						// 举报
						uni.showToast({ title: '举报功能开发中', icon: 'none' })
					}
				}
			})
		},

		// 清空聊天记录
		clearMessages() {
			uni.showModal({
				title: '确认清空',
				content: '确定要清空聊天记录吗？此操作不可恢复',
				success: (res) => {
					if (res.confirm) {
						this.messages = []
					}
				}
			})
		},

		// 获取当前时间
		getCurrentTime() {
			const now = new Date()
			const hours = String(now.getHours()).padStart(2, '0')
			const minutes = String(now.getMinutes()).padStart(2, '0')
			return `${hours}:${minutes}`
		}
	}
}
</script>

<style scoped>
.container {
	height: 100vh;
	display: flex;
	flex-direction: column;
	background: #F5F5F5;
}

/* 聊天头部 */
.chat-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background: #FFFFFF;
	border-bottom: 2rpx solid #E0E0E0;
}

.header-left {
	display: flex;
	align-items: center;
	flex: 1;
}

.user-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.user-info {
	flex: 1;
}

.user-name {
	font-size: 30rpx;
	font-weight: 700;
	color: #333333;
	display: block;
	margin-bottom: 5rpx;
}

.user-status {
	font-size: 22rpx;
	color: #4CAF50;
}

.header-right {
	padding-left: 20rpx;
}

.more-btn {
	font-size: 40rpx;
	color: #666666;
	padding: 0 10rpx;
}

/* 消息列表 */
.message-list {
	flex: 1;
	padding: 20rpx 30rpx;
	background: #F5F5F5;
}

.message-wrapper {
	margin-bottom: 30rpx;
}

/* 时间分割线 */
.time-divider {
	text-align: center;
	margin: 30rpx 0;
}

.time-text {
	font-size: 22rpx;
	color: #999999;
	background: rgba(0, 0, 0, 0.05);
	padding: 5rpx 20rpx;
	border-radius: 15rpx;
}

/* 消息项 */
.message-item {
	display: flex;
	margin-bottom: 25rpx;
}

.message-item.mine {
	flex-direction: row-reverse;
}

.msg-avatar {
	width: 70rpx;
	height: 70rpx;
	border-radius: 50%;
	margin: 0 15rpx;
}

/* 消息内容 */
.message-content {
	max-width: 500rpx;
}

/* 文字消息 */
.text-message {
	background: #FFFFFF;
	padding: 20rpx 25rpx;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.message-item.mine .text-message {
	background: linear-gradient(135deg, #FFB6C1 0%, #FF91A4 100%);
}

.message-text {
	font-size: 28rpx;
	color: #333333;
	line-height: 1.6;
	word-break: break-all;
}

.message-item.mine .message-text {
	color: #FFFFFF;
}

/* 图片消息 */
.image-message {
	max-width: 400rpx;
	max-height: 400rpx;
	border-radius: 15rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

/* 订单消息 */
.order-message {
	background: #FFFFFF;
	border-radius: 15rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	border: 2rpx solid #FFB6C1;
}

.order-header {
	display: flex;
	align-items: center;
	margin-bottom: 15rpx;
	padding-bottom: 10rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.order-icon {
	font-size: 28rpx;
	margin-right: 10rpx;
}

.order-title {
	font-size: 26rpx;
	font-weight: 700;
	color: #333333;
}

.order-info {
	display: flex;
	flex-direction: column;
	gap: 8rpx;
}

.order-pet,
.order-service {
	font-size: 24rpx;
	color: #666666;
}

.order-price {
	font-size: 28rpx;
	color: #FF8C42;
	font-weight: 700;
}

/* 加载更多 */
.load-more {
	text-align: center;
	padding: 20rpx 0;
}

.load-text {
	font-size: 24rpx;
	color: #999999;
}

/* 输入区域 */
.input-area {
	background: #FFFFFF;
	border-top: 2rpx solid #E0E0E0;
	padding-bottom: env(safe-area-inset-bottom);
}

/* 工具栏 */
.toolbar {
	display: flex;
	padding: 15rpx 30rpx;
	gap: 30rpx;
	border-bottom: 1rpx solid #F0F0F0;
}

.tool-btn {
	width: 60rpx;
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #F5F5F5;
	border-radius: 15rpx;
}

.tool-icon {
	font-size: 32rpx;
}

/* 输入框 */
.input-wrapper {
	display: flex;
	align-items: flex-end;
	padding: 15rpx 30rpx;
	gap: 20rpx;
}

.message-input {
	flex: 1;
	min-height: 70rpx;
	max-height: 200rpx;
	background: #F5F5F5;
	border-radius: 20rpx;
	padding: 15rpx 20rpx;
	font-size: 28rpx;
	line-height: 1.5;
}

.send-btn {
	width: 120rpx;
	height: 70rpx;
	background: linear-gradient(135deg, #FFB6C1 0%, #FF91A4 100%);
	color: #FFFFFF;
	border-radius: 20rpx;
	font-size: 26rpx;
	font-weight: 700;
	border: none;
	padding: 0;
	line-height: 70rpx;
}

.send-btn[disabled] {
	background: #E0E0E0;
	color: #999999;
}

/* 快捷回复 */
.quick-replies {
	white-space: nowrap;
	padding: 15rpx 30rpx;
	border-top: 1rpx solid #F0F0F0;
}

.quick-item {
	display: inline-block;
	padding: 10rpx 25rpx;
	background: #F5F5F5;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #666666;
	margin-right: 15rpx;
}
</style>
